<?php

/**
 * BelongsToBehavior class
 * 
 * Advanced belongs to relation because relations didn't support class name from
 * field value.
 *
 * @author Julot
 * @since Saturday, June 16, 2012. 04:34 PM
 */
class DynamicBelongsToBehavior extends CActiveRecordBehavior {

	public $classField;
	public $foreignKeyField;
	private $_model;

	public function getModel() {
		if (!$this->_model) {
			$class = $this->getAttribute($this->classField);
			$model = call_user_func(array($class, 'model'));
			$fk = $this->getAttribute($this->foreignKeyField);
			$this->_model = $model->findByPk($fk);
		}
		return $this->_model;
	}

	private function getAttribute($name) {
		if (empty($name)) {
			throw new CException('Empty attribute property');
		}
		if (!$this->owner->hasAttribute($name)) {
			$s = 'Model ' . get_class($this->owner);
			$s .= ' does not have attribute ' . $name;
			throw new CException($s);
		}
		return $this->owner->getAttribute($name);
	}

	public function __get($name) {
		try {
			return parent::__get($name);
		} catch (Exception $e) {
			return $this->model->$name;
		}
	}

}
